#!/bin/bash

# OTA管理系统数据库初始化脚本
# 使用方法: ./setup_database.sh [mysql|sqlite] [选项]

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_debug() {
    echo -e "${BLUE}[DEBUG]${NC} $1"
}

# 显示帮助信息
show_help() {
    echo "OTA管理系统数据库初始化脚本"
    echo ""
    echo "使用方法:"
    echo "  $0 mysql [选项]    - 初始化MySQL数据库"
    echo "  $0 sqlite [选项]   - 初始化SQLite数据库"
    echo ""
    echo "MySQL选项:"
    echo "  -h, --host HOST     MySQL主机地址 (默认: localhost)"
    echo "  -P, --port PORT     MySQL端口 (默认: 3306)"
    echo "  -u, --user USER     MySQL用户名 (默认: root)"
    echo "  -p, --password PWD  MySQL密码"
    echo "  -d, --database DB   数据库名 (默认: ota_db)"
    echo ""
    echo "SQLite选项:"
    echo "  -f, --file FILE     SQLite数据库文件路径 (默认: ./data/ota.db)"
    echo ""
    echo "通用选项:"
    echo "  --force            强制重新创建数据库"
    echo "  --backup           创建数据库前先备份"
    echo "  --help             显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 mysql -u root -p mypassword"
    echo "  $0 sqlite -f /path/to/database.db"
    echo "  $0 mysql --host 192.168.1.100 --user admin --password secret --force"
}

# 检查依赖
check_dependencies() {
    local db_type=$1
    
    if [ "$db_type" = "mysql" ]; then
        if ! command -v mysql &> /dev/null; then
            log_error "MySQL客户端未安装，请先安装MySQL客户端"
            exit 1
        fi
    elif [ "$db_type" = "sqlite" ]; then
        if ! command -v sqlite3 &> /dev/null; then
            log_error "SQLite3未安装，请先安装SQLite3"
            exit 1
        fi
    fi
}

# 备份数据库
backup_database() {
    local db_type=$1
    local backup_file=""
    
    if [ "$db_type" = "mysql" ]; then
        backup_file="backup_mysql_$(date +%Y%m%d_%H%M%S).sql"
        log_info "正在备份MySQL数据库到 $backup_file"
        mysqldump -h "$MYSQL_HOST" -P "$MYSQL_PORT" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" "$MYSQL_DATABASE" > "$backup_file" 2>/dev/null || {
            log_warn "备份失败，可能是因为数据库不存在"
        }
    elif [ "$db_type" = "sqlite" ]; then
        if [ -f "$SQLITE_FILE" ]; then
            backup_file="backup_sqlite_$(date +%Y%m%d_%H%M%S).db"
            log_info "正在备份SQLite数据库到 $backup_file"
            cp "$SQLITE_FILE" "$backup_file"
        else
            log_warn "SQLite数据库文件不存在，跳过备份"
        fi
    fi
}

# 初始化MySQL数据库
init_mysql() {
    log_info "开始初始化MySQL数据库..."
    
    # 检查连接
    mysql -h "$MYSQL_HOST" -P "$MYSQL_PORT" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "SELECT 1;" &>/dev/null || {
        log_error "无法连接到MySQL服务器，请检查连接参数"
        exit 1
    }
    
    # 执行初始化脚本
    log_info "执行MySQL初始化脚本..."
    mysql -h "$MYSQL_HOST" -P "$MYSQL_PORT" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" < "$(dirname "$0")/init_mysql.sql" || {
        log_error "MySQL初始化脚本执行失败"
        exit 1
    }
    
    log_info "MySQL数据库初始化完成！"
    
    # 显示统计信息
    table_count=$(mysql -h "$MYSQL_HOST" -P "$MYSQL_PORT" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -s -N -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '$MYSQL_DATABASE';" 2>/dev/null || echo "0")
    log_info "数据库: $MYSQL_DATABASE"
    log_info "表数量: $table_count"
}

# 初始化SQLite数据库
init_sqlite() {
    log_info "开始初始化SQLite数据库..."
    
    # 创建目录
    local db_dir=$(dirname "$SQLITE_FILE")
    if [ ! -d "$db_dir" ]; then
        log_info "创建数据库目录: $db_dir"
        mkdir -p "$db_dir"
    fi
    
    # 执行初始化脚本
    log_info "执行SQLite初始化脚本..."
    sqlite3 "$SQLITE_FILE" < "$(dirname "$0")/init_sqlite.sql" || {
        log_error "SQLite初始化脚本执行失败"
        exit 1
    }
    
    log_info "SQLite数据库初始化完成！"
    
    # 显示统计信息
    table_count=$(sqlite3 "$SQLITE_FILE" "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';" 2>/dev/null || echo "0")
    log_info "数据库文件: $SQLITE_FILE"
    log_info "表数量: $table_count"
    log_info "文件大小: $(du -h "$SQLITE_FILE" | cut -f1)"
}

# 主函数
main() {
    if [ $# -eq 0 ]; then
        show_help
        exit 1
    fi
    
    local db_type=$1
    shift
    
    # 默认参数
    MYSQL_HOST="localhost"
    MYSQL_PORT=3306
    MYSQL_USER="root"
    MYSQL_PASSWORD=""
    MYSQL_DATABASE="ota_db"
    SQLITE_FILE="./data/ota.db"
    FORCE_RECREATE=false
    BACKUP_FIRST=false
    
    # 解析参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--host)
                MYSQL_HOST="$2"
                shift 2
                ;;
            -P|--port)
                MYSQL_PORT="$2"
                shift 2
                ;;
            -u|--user)
                MYSQL_USER="$2"
                shift 2
                ;;
            -p|--password)
                MYSQL_PASSWORD="$2"
                shift 2
                ;;
            -d|--database)
                MYSQL_DATABASE="$2"
                shift 2
                ;;
            -f|--file)
                SQLITE_FILE="$2"
                shift 2
                ;;
            --force)
                FORCE_RECREATE=true
                shift
                ;;
            --backup)
                BACKUP_FIRST=true
                shift
                ;;
            --help)
                show_help
                exit 0
                ;;
            *)
                log_error "未知参数: $1"
                show_help
                exit 1
                ;;
        esac
    done
    
    # 验证数据库类型
    if [ "$db_type" != "mysql" ] && [ "$db_type" != "sqlite" ]; then
        log_error "不支持的数据库类型: $db_type"
        show_help
        exit 1
    fi
    
    # 检查依赖
    check_dependencies "$db_type"
    
    # 如果MySQL需要密码但未提供，则提示输入
    if [ "$db_type" = "mysql" ] && [ -z "$MYSQL_PASSWORD" ]; then
        read -s -p "请输入MySQL密码: " MYSQL_PASSWORD
        echo
    fi
    
    # 备份数据库
    if [ "$BACKUP_FIRST" = true ]; then
        backup_database "$db_type"
    fi
    
    # 初始化数据库
    case $db_type in
        mysql)
            init_mysql
            ;;
        sqlite)
            init_sqlite
            ;;
    esac
    
    log_info "数据库初始化完成！"
}

# 执行主函数
main "$@" 